package com.example.base.config.handler;



import com.example.base.system.domain.SysLog;
import com.example.base.system.service.SysLogService;
import com.example.base.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname GlobalInterceptor
 * @Description TODO
 * @Date 2023/9/17 3:39
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@Slf4j
public class GlobalInterceptor implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse resp=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取处理器的类名
            String className = handlerMethod.getBeanType().getName();
            // 获取处理器的方法名
            String methodName = handlerMethod.getMethod().getName();
            // 可以根据需要获取其他信息，比如方法参数、注解等
            System.out.println("正在访问的处理器类：" + className);
            System.out.println("正在访问的处理器方法：" + methodName);
        }



        log.info("全局拦截访问: {}",req.getRequestURI());

        // 在请求处理之前进行拦截操作
        return true; // 返回true继续执行请求，返回false中断请求
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // 请求处理之后进行拦截操作，可以在这里修改ModelAndView等
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        // 在请求处理完成后进行拦截操作，可以做一些资源清理工作
        log.info("请求处理完成后:{}",handler.getClass());

        SysLogService sysLogService=SpringContextUtils.getBean(SysLogService.class);
        if(handler instanceof HandlerMethod){
            sysLogService.operateSysLog(request,response,(HandlerMethod)handler,ex);
        }
        //清除登录信息
        com.example.base.security.SecurityUtil.removeSysUserEntity();
    }

}
